import React, { useEffect, useState } from "react";
import { Layout, Menu } from "antd";
import type { MenuProps } from "antd";
import { routes } from "@/config/routes";
import { useDispatch, useSelector } from "react-redux";
import { setSelectedKeys, setOpenKeys, addTag } from "@/store/menuSlice";
import { RootState } from "@/store/store";
import { RouteType } from "@/types/route";
import { useNavigate } from "react-router-dom";
import * as Icons from "@ant-design/icons";

const { Sider } = Layout;
type MenuItem = Required<MenuProps>["items"][number];

// 动态获取图标组件
function getIcon(name: string) {
  const Icon: any = Icons;
  return React.createElement(Icon[name]);
}

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[]
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem;
}

const Side: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { selectedKeys, openKeys } = useSelector(
    (state: RootState) => state.menu
  );
  const [collapsed, setCollapsed] = useState(false);

  // 将 routes 转换为 MenuItems
  const convertToMenuItems = (data: RouteType[]): MenuItem[] => {
    return data
      .filter((item) => !item.hidden) // 过滤掉隐藏的路由
      .map((item) => {
        const { key, label, icon, children } = item;
        // 如果有子路由
        if (children && children.length > 0) {
          return getItem(
            label,
            key,
            icon ? getIcon(icon) : "", // 如果存在图标则添加
            convertToMenuItems(children) // 递归处理子路由
          );
        }
        // 没有子路由
        return getItem(
          label,
          key,
          icon ? getIcon(icon) : "" // 如果存在图标则添加
        );
      });
  };

  const menu = routes.find((item) => item.key === "content")?.children;

  const items = convertToMenuItems(menu as RouteType[]);

  useEffect(() => {
    const savedSelectedKeys = sessionStorage.getItem("selectedKeys");
    const savedOpenKeys = sessionStorage.getItem("openKeys");

    if (savedSelectedKeys) {
      dispatch(setSelectedKeys(JSON.parse(savedSelectedKeys)));
    }
    if (savedOpenKeys) {
      dispatch(setOpenKeys(JSON.parse(savedOpenKeys)));
    }
  }, [dispatch]);

  // 查找最底层子节点
  const findLeafNodes = (key: string, data: RouteType[]): RouteType[] => {
    let result: RouteType[] = [];
    for (const item of data) {
      if (item.key === key && (!item.children || item.children.length === 0)) {
        result.push(item);
      } else if (item.children) {
        result = result.concat(findLeafNodes(key, item.children));
      }
    }
    return result;
  };

  const clickMenu = (e: any) => {
    navigate(e.key);
    dispatch(setSelectedKeys([e.key]));
    sessionStorage.setItem("selectedKeys", JSON.stringify([e.key]));

    // 查找当前点击菜单项的最底层子节点数据
    const leafNodes = findLeafNodes(e.key, routes);
    // 对首页进行过滤处理
    const filteredLeafNodes = leafNodes.filter((item) => item.key !== "home");
    filteredLeafNodes.forEach((node) => {
      const tag = { key: node.key, name: node.label as string };
      dispatch(addTag(tag));
    });
  };

  const onOpenChange = (keys: string[]) => {
    dispatch(setOpenKeys(keys));
    sessionStorage.setItem("openKeys", JSON.stringify(keys));
  };

  return (
    <Sider
      collapsible
      collapsed={collapsed}
      onCollapse={(value) => setCollapsed(value)}
      style={{
        // overflow: "auto",
        height: "100vh",
        position: "fixed",
        // insetInlineStart: 0,
        top: 0,
        bottom: 0,
        // scrollbarWidth: "thin",
        // scrollbarColor: "unset",
      }}
    >
      <div className="demo-logo-vertical" style={{ height: "60px" }}></div>
      <Menu
        theme="dark"
        selectedKeys={selectedKeys}
        openKeys={openKeys}
        onClick={clickMenu}
        onOpenChange={onOpenChange}
        style={{ height: "100%", borderRight: 0 }}
        mode="inline"
        items={items}
      />
    </Sider>
  );
};

export default Side;
